(function () {
    //房间用到的字体文件
    var FontRes = [
        {url : "res/font/font_win.fnt", name : "font_win"},
        {url : "res/font/font_special.fnt", name : "font_special"},
        {url : "res/font/font_seat.fnt", name : "font_seat"},
        {url : "res/font/font_lose.fnt", name : "font_lose"},
        {url : "res/font/font_compare.fnt", name : "font_compare"},
        {url : "res/font/font_card_type.fnt", name : "font_card_type"},
        {url : "res/font/font_card_num.fnt", name : "font_card_num"}
    ];

    /**
     * 房间管理器
     * 包含 注册房间资源，创建默认玩家座位，绑定事件，更新房间数据，更新当前用户的游戏状态等
     */
    function RoomController() {
        this.RoomID = null;
        this.RoomUI = null;
        this.RoomBG = null;
        this.SeatPanel = null;
        this.TimerReady = null;
        this.UserID = null;
        this.UserSeatID = null;
        this.Seats = {};
        this.Stage = null;
        this.btnLock = false;
        this.tableStatus = null;
        
        viewer.register("arena.start", this.start.bind(this));
        viewer.register("arena.resize", this.resize.bind(this));
        viewer.register("room.loaded", this.init.bind(this));
        viewer.register("room::into", this.roomInto.bind(this));
        viewer.register("room::ready", this.userReady.bind(this));
        viewer.register("room::readyCancel", this.userCancelReady.bind(this));
        viewer.register("room::leaveTable", this.leaveRoom.bind(this));
        viewer.register("game::started", this.gameStart.bind(this));
        viewer.register("game::waiting", this.gameWaiting.bind(this));
    }

    var _proto = RoomController.prototype;
    /**
     * @privite
     * 注册房间页用到的BMFont字体
     */
    _proto.regAssets = function () {
        for(var i in FontRes){
            (function (font) {
                var bitmapFont = new Laya.BitmapFont();
                bitmapFont.loadFont(font.url);
                Laya.Text.registerBitmapFont(font.name, bitmapFont);
            })(FontRes[i]);
        }
    }
    /**
     * @privite
     * 创建房间UI及控件，包含房间主UI界面，准备倒计时，默认玩家座位
     */
    _proto.createUI = function () {
        var Seats = this.Seats;
        var Stage = this.Stage;

        this.TimerReady = new ui.Com.TimerReady();

        var RoomBG = new ui.Room.RoomBGUI();
        RoomBG.width = Stage.width;
        RoomBG.height = Stage.height;
        this.RoomBG = RoomBG;
        
        var RoomUI = new ui.Room.RoomPageUI();
        RoomUI.btnCancelReady.y = 1390;
        RoomUI.btnCancelReady.alpha = 0;
        RoomUI.btnReady.y = 1390;
        RoomUI.btnReady.alpha = 0;
        RoomUI.btnChangeTable.y = 1390;
        RoomUI.btnChangeTable.alpha = 0;
        RoomUI.btnChat.alpha = 0;
        this.RoomUI = RoomUI;

        var SeatPanel = new Laya.Component();
        SeatPanel.name = "seat.panel";
        SeatPanel.width = 750;
        SeatPanel.height = 1334;
        SeatPanel.centerX = 0;
        SeatPanel.y = 0;
        SeatPanel.mouseEnabled = true;
        SeatPanel.mouseThrough = true;
        this.SeatPanel = SeatPanel;

        Stage.removeChildren();
        Stage.addChildren(RoomBG, RoomUI, this.TimerReady, SeatPanel);

        
        for(var i = 1; i <= 4; i++){
            var _seat = new ui.Com.Seat(i);
            
            SeatPanel.addChild(_seat);
            Seats[i] = _seat;
        }
    }
    /**
     * @privite
     * 绑定事件
     */
    _proto.bindEvent = function () {
        var RoomUI = this.RoomUI;

        //声音
        new ui.Com.BtnSound(RoomUI.btnSound, RoomUI.btnSound);

        //返回大厅
        RoomUI.btnBack.on(Laya.Event.CLICK, this, function () {
            if(this.UserSeatID && this.Seats[this.UserSeatID].status == "gaming"){
                var param = {
                    message : "您尚在游戏中，现在退出将进行自动比牌结算。",
                    closeHandler : function () {
                        viewer.publish("io.emit", {
                            cmd : "room::leaveTable",
                            params : {
                                token : token
                            }
                        });
                    }
                }

                viewer.publish("alert.show", "normal", param);
            }else{
                viewer.publish("io.emit", {
                    cmd : "room::leaveTable",
                    params : {
                        token : token
                    }
                });
            }
            utils.log("点击了返回大厅按钮");
        });

        //换桌
        RoomUI.btnChangeTable.on(Laya.Event.CLICK, this, function () {
            if(this.btnLock){
                viewer.publish("alert.tip", "您点击的太快了。", 2000, 0.7);
                return;
            }
            viewer.publish("alert.tip.close");
            this.lockButton();

            viewer.publish("io.emit", {
                cmd : "room::changeTable",
                params : {
                    token : token,
                    roomId : this.RoomID
                }
            });
            utils.log("点击了换桌按钮，RoomID:" + this.RoomID);
        });

        //准备
        RoomUI.btnReady.on(Laya.Event.CLICK, this, function () {
            if(this.btnLock){
                viewer.publish("alert.tip", "您点击的太快了。", 2000, 0.7);
                return;
            }
            viewer.publish("alert.tip.close");
            this.lockButton();

            viewer.publish("io.emit", {
                cmd : "room::ready",
                params : {
                    token : token
                }
            });
            utils.log("点击了准备按钮");
        });

        //取消准备
        RoomUI.btnCancelReady.on(Laya.Event.CLICK, this, function () {
            if(this.btnLock){
                viewer.publish("alert.tip", "您点击的太快了。", 2000, 0.7);
                return;
            }
            viewer.publish("alert.tip.close");
            this.lockButton();

            viewer.publish("io.emit", {
                cmd : "room::readyCancel",
                params : {
                    token : token
                }
            });
            utils.log("点击了取消准备按钮");
        });

        //聊天
        RoomUI.btnChat.on(Laya.Event.CLICK, null, function () {
            viewer.publish("alert.show", "chat");
            utils.log("点击了聊天按钮");
        });
    }
    _proto.lockButton = function () {
        this.btnLock = true;
        setTimeout(function () {
            this.btnLock = false;
        }.bind(this), 1000);
    }
    
    /**
     * @public
     * 初始化房间，包含注册房间字体资源，创建房间界面，绑定事件，推送进入房间命等
     * 
     * @param {Number} RoomID 房间ID
     */
    _proto.init = function (RoomID) {

        var params = {
            token : token
        };
        this.RoomID = RoomID;

        this.regAssets();
        this.createUI();
        this.bindEvent();

        if(RoomID !== void 0){
            params.roomId = RoomID;
        }
        viewer.publish("io.emit", {
            cmd : "room::into",
            params : params
        });
    }

    /**
     * 接收room::into消息，初始化房间信息
     * 包含底分，TableID，RoomID
     * @params res {object} 房间信息
     */
    _proto.roomInto = function (res) {
        if(Arena.CurScene !== "room"){return;}
        utils.log("RoomController.roomInto");
        
        var RoomUI = this.RoomUI;
        var UserID = this.UserID;

        var timeout = res.timeout || 20000;
        var players = res.list;

        this.RoomID = res.roomId;
        this.tableStatus = res.tableStatus | 0;

        for(var i in players){
            var player = players[i];
            if(player.uid == 0){continue;}
            
            if(player.uid == UserID){
                this.UserSeatID = player.position;
                switch(player.gameStatus | 0){
                    case 1:
                        this.userCancelReady({timeout : timeout, position : player.position});
                        break;
                    case 2:
                        this.userReady({position : player.position});
                        break;
                    case 3:
                    case 4:
                    case 5:
                        RoomUI.btnCancelReady.visible = false;
                        RoomUI.btnReady.visible = false;
                        RoomUI.btnChangeTable.visible = false;
                        break;
                }
            }
        }

        RoomUI.betCoin.text = res.bottom + " 游戏币/分";
        RoomUI.level.skin = "res/room/room_level_" + this.RoomID + ".png";
        RoomUI.level.alpha = 0;
        RoomUI.level.scale(1.5, 1.5);

        RoomUI.betCoin.visible = true;
        RoomUI.level.visible = true;

        Laya.Tween.to(RoomUI.level, {scaleX : 1, scaleY : 1, alpha : 1}, 200, Laya.Ease.circIn);
        Laya.Tween.to(RoomUI.btnCancelReady, {y : 1206, alpha : 1}, 1000, Laya.Ease.circIn);
        Laya.Tween.to(RoomUI.btnReady, {y : 1206, alpha : 1}, 1000, Laya.Ease.circIn);
        Laya.Tween.to(RoomUI.btnChangeTable, {y : 1206, alpha : 1}, 1000, Laya.Ease.circIn);
        Laya.Tween.to(RoomUI.btnChat, {alpha : 1}, 700, Laya.Ease.circIn);
    }
    /**
     * 接收room::ready消息，用户已准备
     * @params res {object} 已准备的用户信息
     */
    _proto.userReady = function (res) {
        if(Arena.CurScene !== "room"){return;}
        var position = res.position;
        var RoomUI = this.RoomUI;

        if(position == this.UserSeatID){
            this.TimerReady.stop();
            RoomUI.btnCancelReady.visible = true;
            RoomUI.btnReady.visible = false;
        }
    }
    /**
     * 接收room::readyCancel消息，用户取消准备
     * @params res {object} 取消准备的用户信息
     */
    _proto.userCancelReady = function (res) {
        if(Arena.CurScene !== "room"){return;}
        utils.log("RoomController.userCancelReady");

        var timeout = res.timeout || 20000;
        var position = res.position;
        var RoomUI = this.RoomUI;

        if(position == this.UserSeatID){
            timeout = timeout / 1000 | 0;
            this.TimerReady.start(timeout);
            
            RoomUI.btnCancelReady.visible = false;
            RoomUI.btnReady.visible = true;
        }
    }
    /**
     * 接收room::leaveTable消息，用户返回大厅页
     */
    _proto.leaveRoom = function () {
        if(Arena.CurScene !== "room"){return;}
        
        this.TimerReady.stop();
        this.Stage.removeChild(this.TimerReady);

        this.roomId = null;
        this.RoomLevel = null;
        this.Seats = {};
        this.UserSeatID = null;
        this.RoomBG = null;
        this.RoomUI = null;
        this.SeatPanel = null;
        this.TimerReady = null;
        this.tableStatus = null;


        viewer.publish("loader.load", "home");
    }
    /**
     * 接收game::started消息，游戏开始
     * 隐藏 换桌、取消准备、准备 按钮
     */
    _proto.gameStart = function (res) {
        if(Arena.CurScene !== "room"){return;}
        var RoomUI = this.RoomUI;
        var positions = res.position;
        var UserSeatID = this.UserSeatID;

        for(var i in positions){
            if(positions[i] == UserSeatID){
                RoomUI.btnCancelReady.visible = false;
                RoomUI.btnReady.visible = false;
                RoomUI.btnChangeTable.visible = false;
                return;
            }
        }

    }
    /**
     * 接收game::waiting消息，游戏结束，等待开始
     * 显示 换桌、准备 按钮
     * @params res {object} 等待游戏开始相关
     */
    _proto.gameWaiting = function (res) {
        if(Arena.CurScene !== "room"){return;}
        var inGame = false;
        var mySeat = this.Seats[this.UserSeatID];
        utils.log("gameWaiting:" + mySeat.status);

        if(mySeat.status == "ready" || mySeat.status == "cancel"){return;}

        var timeout = res.timeout || 20000;
        var RoomUI = this.RoomUI;

        RoomUI.btnChangeTable.visible = true;
        RoomUI.btnReady.visible = true;
        RoomUI.btnCancelReady.visible = false;

        timeout = timeout / 1000 | 0;
        this.TimerReady.start(timeout);
    }
    /**
     * @public
     * 游戏开始时监听arena.start消息，初始化相关变量
     */
    _proto.start = function () {
        this.Stage = Arena.Stage;
        this.UserID = Arena.UserID;
    }
    /**
     * @public
     * 监听arena.resize消息，重置界面位置
     */
    _proto.resize = function () {
        if(!this.RoomBG){return;}
        this.RoomBG.width = Laya.stage.width;
        this.RoomBG.height = Laya.stage.height;

        this.RoomUI.centerX = 0;

        this.SeatPanel.centerX = 0;
        this.TimerReady.centerX = 0;
    }

    new RoomController();
})();